﻿using System;
using System.Diagnostics;

namespace Simp.Model.CoreExpressions
{
	/// <summary>Encapsulates a square root expression.</summary>
	[ExpressionName("Sqrt")]
	[ParameterPolicy("x")]
	[DebuggerDisplay("{ExpressionHelper.Serialize(this)}")]
	public class SqrtExpression : IExpression, ISimplifiableExpression
	{
		#region ISimplifiableExpression Members
		IExpression ISimplifiableExpression.Simplify(SimplificationMode simplificationMode, params IExpression[] parameterList)
		{
			if (parameterList == null)
			{
				throw new ArgumentNullException("parameterList");
			}
			if (parameterList.Length == 1)
			{
				IExpression expression = parameterList[0];
				INumericExpression numericExpression = expression as INumericExpression;

				if (numericExpression != null)
				{
					RealExpression realExpression =
						numericExpression.GetReal(simplificationMode == SimplificationMode.AllowApproximation);

					if (realExpression != null)
					{
						return new RealExpression(Math.Sqrt(realExpression.Value));
					}
				}
			}

			return null;
		}
		#endregion
	}
}